﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using PhysicalSynchronization.Models;
using PhysicalSynchronization.IBLL;
using PhysicalSynchronization.BLLContainer;
using PhysicalSynchronization.Core;
using MvcWeb.Models;
using System.Net;
using System.IO;
using System.Xml;
using System.Configuration;
using System.Data.Common;
using System.Data.SqlClient;
using System.Text;
using PhysicalSynchronization.Models.ExtentionModel;
using log4net;

namespace MvcWeb.Controllers
{
    public class HomeController : Controller
    {
        private IT_SINGLE_CHECKINFOService TSINGLECHECKINFOService = Container.Resolve<IT_SINGLE_CHECKINFOService>();
        private IT_SINGLE_ANALYZEService TSINGLEANALYZEService = Container.Resolve<IT_SINGLE_ANALYZEService>();
        private IT_EMPService TEMPService = Container.Resolve<IT_EMPService>();
        private IT_SINGLE_DIAGNOSEService TSINGLEDIAGNOSEService = Container.Resolve<IT_SINGLE_DIAGNOSEService>();
        private IT_SINGLE_RESULTService TSINGLERESULTService = Container.Resolve<IT_SINGLE_RESULTService>();
        private IT_CHECKUNITService TCHECKUNITService = Container.Resolve<IT_CHECKUNITService>();
        private IT_CHECKITEMService TCHECKITEMService = Container.Resolve<IT_CHECKITEMService>();
        private string departName = ConfigurationManager.AppSettings["depart"].ToString();
        ILog logWriter = LogManager.GetLogger("HomeController");
        public ActionResult Index()
        {
            return View();
        }
        [HttpPost]
        public JsonData ScanTijian()
        {
            DateTime opdate = DateTime.Now.AddDays(-1);
            List<T_SINGLE_CHECKINFO> checkInfoList = TSINGLECHECKINFOService.GetModels(s => s.APPSYNCSTATUS == 0 && s.OPERATEDATE >= opdate).ToList();//
            List<T_SINGLE_CHECKINFO> tscList = new List<T_SINGLE_CHECKINFO>();
            foreach (T_SINGLE_CHECKINFO model in checkInfoList)
            {
                if (int.Parse(model.CHECKSTATUS) >= 1100 && int.Parse(model.CHECKSTATUS) != 1999)
                {
                    tscList.Add(model);
                }
            }
            
            T_SINGLE_CHECKINFO checkInfo = tscList.FirstOrDefault();
            
            if (checkInfo != null)
            {
                string jsonResult = PostTiJianJson(checkInfo);
                var objResult = JsonHelper.ParseFormJson<ReturnResult>(jsonResult);
                if (objResult.errCode == 0)
                {
                    checkInfo.APPSYNCSTATUS = 1;
                    if (TSINGLECHECKINFOService.Update(checkInfo))
                    {
                        return new JsonData { IsSuccess=true,Message="体检记录同步成功" };
                    }
                    else
                    {
                        return new JsonData { IsSuccess = false, Message = "体检记录同步失败" };
                    }
                }
                if (objResult.errCode == 1)
                {
                    return new JsonData { IsSuccess = false, Message = "服务端异常" };
                }
                if (objResult.errCode == -10)
                {
                    checkInfo.APPSYNCSTATUS = 1;
                    if (TSINGLECHECKINFOService.Update(checkInfo))
                    {
                        return new JsonData { IsSuccess = true, Message = "体检记录同步成功" };
                    }
                    else
                    {
                        return new JsonData { IsSuccess = false, Message = "体检记录同步失败" };
                    }
                }
                if (objResult.errCode == -11)
                {
                    checkInfo.APPSYNCSTATUS = 2;//未实名认证
                    if (TSINGLECHECKINFOService.Update(checkInfo))
                    {
                        return new JsonData { IsSuccess = true, Message = "用户"+checkInfo.SGLCHECKID+"未进行实名认证，体检记录同步成功" };
                    }
                    else
                    {
                        return new JsonData { IsSuccess = false, Message = "用户" + checkInfo.SGLCHECKID + "未进行实名认证，体检记录同步失败" };
                    }
                }
                if (objResult.errCode == -12)
                {
                    checkInfo.APPSYNCSTATUS = 3;//用户身份证号不存在
                    if (TSINGLECHECKINFOService.Update(checkInfo))
                    {
                        return new JsonData { IsSuccess = true, Message = "用户" + checkInfo.SGLCHECKID + "缺少用户IdCard证信息，体检记录同步成功" };
                    }
                    else
                    {
                        return new JsonData { IsSuccess = false, Message = "用户" + checkInfo.SGLCHECKID + "缺少用户IdCard证信息，体检记录同步失败" };
                    }
                }
                if (objResult.errCode == -1)
                {
                    checkInfo.APPSYNCSTATUS = 4;//接口返回异常
                    if (TSINGLECHECKINFOService.Update(checkInfo))
                    {
                        return new JsonData { IsSuccess = true, Message = "用户" + checkInfo.SGLCHECKID + "程序异常，体检记录同步成功" };
                    }
                    else
                    {
                        return new JsonData { IsSuccess = false, Message = "用户" + checkInfo.SGLCHECKID + "程序异常，体检记录同步失败" };
                    }
                }
            }
            return new JsonData { IsSuccess = false, Message = "没有可以同步的数据" };
        }

        public string PostTiJianJson(T_SINGLE_CHECKINFO tsinglecheckinfoModel)
        {
            string jsonResult = "";
            try
            {
                string idcarddes = RandomHelper.RndNum(4) + tsinglecheckinfoModel.IDCARD + RandomHelper.RndNum(4);//"140622199202149835"
                idcarddes = System.Web.HttpUtility.UrlEncode(DesEncryptHelper.AesEncrypt(idcarddes, "CIMINGTJCIMINGTJ"));
                string mobiledes = RandomHelper.RndNum(4) + tsinglecheckinfoModel.MOBILEPHONE + RandomHelper.RndNum(4);//"15678948405"tsinglecheckinfoModel.MOBILEPHONE
                mobiledes = System.Web.HttpUtility.UrlEncode(DesEncryptHelper.AesEncrypt(mobiledes, "CIMINGTJCIMINGTJ"));
                T_SINGLE_ANALYZE tsingleanalyze = TSINGLEANALYZEService.GetModels(a => a.SGLCHECKID == tsinglecheckinfoModel.SGLCHECKID).FirstOrDefault();
                T_EMP temp = TEMPService.GetModels(e => e.FID == tsingleanalyze.ANALYZEDOCTOR).FirstOrDefault();

                string diaSql = "select c.FNAME as AuditdoctorName,a.DIAGRESULT,d.CHECKUNITNAME as UnitName,b.FNAME as CheckdoctorName,a.SGLCHECKID,d.CHECKUNITID as UnitId,d.PRINCTCONTENT from T_SINGLE_DIAGNOSE a left join T_EMP b on a.CHECKDOCTOR = b.FID left join T_EMP c on a.VALIDDOCTOR = c.FID join T_CHECKUNIT d on a.CHECKUNITID = d.CHECKUNITID join (select SGLCHECKID,CHECKUNITID,max(MYROWID) as ROWID from T_SINGLE_DIAGNOSE where SGLCHECKID = @sglcheckid1 and CHECKUNITID in (select distinct c.CHECKUNITID from T_SINGLE_RESULT a join T_CHECKITEM b on a.CHECKITEMID=b.CHECKITEMID join T_CHECKUNIT c on b.CHECKUNITID=c.CHECKUNITID where a.SGLCHECKID = @sglcheckid2) group by SGLCHECKID,CHECKUNITID) aaa on a.SGLCHECKID = aaa.SGLCHECKID and a.MYROWID = aaa.ROWID and a.CHECKUNITID=aaa.CHECKUNITID";

                var args = new SqlParameter[] {
                    new SqlParameter {ParameterName = "sglcheckid1", Value = tsinglecheckinfoModel.SGLCHECKID},
                    new SqlParameter {ParameterName = "sglcheckid2", Value = tsinglecheckinfoModel.SGLCHECKID}
                };
                List<T_MiddleDIAGNOSE> MiddleUnitModelList = SqlHelper.GetModelsBySql<T_MiddleDIAGNOSE>(diaSql, args);

                //20170706加 名词解释
                string disSql = "SELECT b.BRIEFNAME,b.DISDEFINE,b.DISEASEID FROM T_SINGLE_DISSUM a join T_DISEASEDICT b on a.DISEASEID = b.DISEASEID where a.SGLCHECKID = @sglcheckid1 ";
                var args_dis = new SqlParameter[] {
                    new SqlParameter {ParameterName = "sglcheckid1", Value = tsinglecheckinfoModel.SGLCHECKID}
                };
                List<T_DISEASEDICT> DISEASEDICTList = SqlHelper.GetModelsBySql<T_DISEASEDICT>(disSql, args_dis);
                StringBuilder sb_diseasedict = new StringBuilder();
                StringBuilder errorCode = new StringBuilder();
                if (DISEASEDICTList != null)
                {
                    foreach (T_DISEASEDICT dict in DISEASEDICTList)
                    {
                        errorCode.Append(dict.DISEASEID).Append(",");
                        if (!string.IsNullOrEmpty(dict.DISDEFINE))
                        {
                            sb_diseasedict.Append(dict.BRIEFNAME).Append("：").Append(dict.DISDEFINE).Append("\r\n");
                        }
                    }
                }

                List<TiJianItems> tijianItemsList = new List<TiJianItems>();

                foreach (var unitModel in MiddleUnitModelList)
                {
                    string itemSql = "select a.ITEMRESULT,a.UNIT,a.RSLTFLAG,a.HIGHCRITICAL,a.CRITICALNAME,b.CHECKITEMNAME,c.CHECKUNITNAME,a.LOWCRITICAL,a.SGLCHECKID,c.CHECKUNITID from T_SINGLE_RESULT a join T_CHECKITEM b on a.CHECKITEMID=b.CHECKITEMID join T_CHECKUNIT c on b.CHECKUNITID=c.CHECKUNITID where a.SGLCHECKID = @sglcheckid and c.CHECKUNITID = @unitid";
                    var items = new SqlParameter[] {
                    new SqlParameter {ParameterName = "sglcheckid", Value = tsinglecheckinfoModel.SGLCHECKID},
                    new SqlParameter{ParameterName = "unitid", Value = unitModel.UnitId}
                };
                    List<T_MiddleRESULT> MiddleResultList = SqlHelper.GetModelsBySql<T_MiddleRESULT>(itemSql, items);
                    List<TiJianUnits> tijianUnitsList = new List<TiJianUnits>();
                    foreach (var itemModel in MiddleResultList)
                    {
                        TiJianUnits tijianUnit = new TiJianUnits();
                        tijianUnit.diagResult = itemModel.ITEMRESULT;
                        tijianUnit.unit = itemModel.UNIT;
                        tijianUnit.rsltflag = itemModel.RSLTFLAG;
                        tijianUnit.highCritical = itemModel.HIGHCRITICAL;
                        tijianUnit.criticalName = itemModel.CRITICALNAME;
                        tijianUnit.checkitemName = itemModel.CHECKUNITNAME;
                        tijianUnit.checkunitName = itemModel.CHECKITEMNAME;
                        tijianUnit.lowCritical = itemModel.LOWCRITICAL;
                        tijianUnit.imgs = "";
                        tijianUnit.resultType = "1";
                        tijianUnitsList.Add(tijianUnit);
                    }

                    TiJianItems tijianItem = new TiJianItems();
                    tijianItem.auditdoctorName = unitModel.AuditdoctorName;
                    tijianItem.itemResult = unitModel.PRINCTCONTENT.Equals("0") ? unitModel.DIAGRESULT : "";
                    tijianItem.checkitemName = unitModel.UnitName;
                    tijianItem.checkdoctorName = unitModel.CheckdoctorName;
                    tijianItem.showType = unitModel.PRINCTCONTENT;  //20170706加 显示类型  0 项目-检查所见，1 项目-结果-单位-参考范围，2 描述
                    tijianItem.units = tijianUnitsList;
                    tijianItemsList.Add(tijianItem);
                }
                string strerrorcode = errorCode.ToString();
                TiJianResults tijianResult = new TiJianResults
                {
                    checkTime = tsinglecheckinfoModel.REGISTDATE.ToString(),
                    summarydoctorName = temp.FNAME,
                    idcard = idcarddes,
                    analyzeAdvice = tsingleanalyze.ANALYZEADVICE,
                    depart = departName,
                    sglcheckid = tsinglecheckinfoModel.SGLCHECKID,
                    mobile = mobiledes,
                    reportAnalysis = sb_diseasedict.ToString(),    //20170706加名词解释
                    errorcode = string.IsNullOrEmpty(strerrorcode) ? "" : strerrorcode.Substring(0, strerrorcode.Length - 1),//疾病编码
                    items = tijianItemsList
                };

                string strUrl = ConfigurationManager.AppSettings["strUrl"].ToString();
                jsonResult = JsonHelper.GetJson(tijianResult);
            }
            catch (Exception ex)
            {
                tsinglecheckinfoModel.APPSYNCSTATUS = 1;
                TSINGLECHECKINFOService.Update(tsinglecheckinfoModel);
                jsonResult = "{\"msg\": \"异常" + ex.Message + "\",\"data\": {},\"errCode\": \"-1\"}";
                throw;
            }

            return jsonResult;
        }

        public string Post(string strURL, string jsonParas)
        {
            //创建一个HTTP请求  
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(strURL);
            //Post请求方式  
            request.Method = "POST";
            //内容类型
            request.ContentType = "application/x-www-form-urlencoded";
            //request.ContentType = "text/html";
            //设置参数，并进行URL编码  
            //虽然我们需要传递给服务器端的实际参数是JsonParas(格式：[{\"UserID\":\"0206001\",\"UserName\":\"ceshi\"}])，
            //最后将字符串参数进行Url编码
            string paraUrlCoded = "info";
            paraUrlCoded += "=" + System.Web.HttpUtility.UrlEncode(jsonParas);
            
            byte[] payload;
            //将Json字符串转化为字节  
            payload = System.Text.Encoding.UTF8.GetBytes(paraUrlCoded);
            //设置请求的ContentLength
            request.ContentLength = payload.Length;
            //发送请求，获得请求流
            Stream writer;
            try
            {
                writer = request.GetRequestStream();//获取用于写入请求数据的Stream对象
            }
            catch (Exception)
            {
                writer = null;
                Console.Write("连接服务器失败!");
            }
            //将请求参数写入流
            writer.Write(payload, 0, payload.Length);
            writer.Close();//关闭请求流

            HttpWebResponse response;
            try
            {
                //获得响应流
                response = (HttpWebResponse)request.GetResponse();
            }
            catch (WebException ex)
            {
                response = ex.Response as HttpWebResponse;
            }

            Stream s = response.GetResponseStream();

            Stream postData = Request.InputStream;
            StreamReader sRead = new StreamReader(s);
            string postContent = sRead.ReadToEnd();
            sRead.Close();
            if (JsonHelper.ParseFormJson<ReturnResult>(postContent).errCode != 0)
            {
                logWriter.Error("ErrCode：错误代码1，" + "传入内容：" + jsonParas);
            }
            return postContent;//返回Json数据
        }
    }
}